<?php

namespace app\admin\controller\pay;

use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Log;

/**
 * 支付商户管理
 *
 * @icon fa fa-circle-o
 */
class Merchant extends Backend
{

    /**
     * Merchant模型对象
     * @var \app\admin\model\pay\Merchant
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\pay\Merchant;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("wechatList", $this->model->getWechatList());
        $this->view->assign("noPasswordList", $this->model->getNoPasswordList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $hooks = config('addons.hooks');
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!empty($hooks['upload_config_init'])) {
            $third = get_addon_config($hooks['upload_config_init'][0]);
            
            $remotefile = fopen($third['cdnurl']. $file, 'r');
            $dirpath = dirname($filePath);
            if (!is_dir($dirpath)) {
                mkdir($dirpath,0777,true);
            }
            $fh = fopen($filePath, 'w');

            while (!feof($remotefile)) {
                $output = fread($remotefile, 8192);
                fwrite($fh, $output);
            }
            fclose($remotefile);
        }

        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //加载文件
        $insert = [];
        $exists = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);

            $preasync_key = '';//异步通知key
            $prewechat_code = '';//商户激活码
            $prebusiness_password = '';//营业员密码
            $preno_password = '1';//是否免密
            // Log::info($allRow);
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $name = $currentSheet->getCellByColumnAndRow(1, $currentRow)->getValue();//商户名
                $type = $currentSheet->getCellByColumnAndRow(2, $currentRow)->getValue();//类型
                $mchid = $currentSheet->getCellByColumnAndRow(3, $currentRow)->getValue();//商户号
                $provinceCity = $currentSheet->getCellByColumnAndRow(4, $currentRow)->getValue();//商户归属地
                $wechat = $currentSheet->getCellByColumnAndRow(5, $currentRow)->getValue();//微信开户意愿
                $alipay = $currentSheet->getCellByColumnAndRow(6, $currentRow)->getValue();//支付宝开户意愿
                $store = $currentSheet->getCellByColumnAndRow(7, $currentRow)->getValue();//门店名称
                $code = $currentSheet->getCellByColumnAndRow(8, $currentRow)->getValue();//Code
                $business_account = $currentSheet->getCellByColumnAndRow(9, $currentRow)->getValue();//营业员账号
                $refund_password = $currentSheet->getCellByColumnAndRow(10, $currentRow)->getValue();//退款密码
                $wechat_account = $currentSheet->getCellByColumnAndRow(11, $currentRow)->getValue();//微信商户号
                $ali_account = $currentSheet->getCellByColumnAndRow(12, $currentRow)->getValue();//支付宝商户号
                $async_key = $currentSheet->getCellByColumnAndRow(13, $currentRow)->getValue();//异步通知key
                $wechat_code = $currentSheet->getCellByColumnAndRow(14, $currentRow)->getValue();//商户激活码
                $business_password = $currentSheet->getCellByColumnAndRow(15, $currentRow)->getValue();//营业员密码
                $no_password = $currentSheet->getCellByColumnAndRow(16, $currentRow)->getValue();//是否免密
                // Log::info('省份城市：'.$provinceCity);
                if (!$provinceCity || !strstr($provinceCity,'-')) continue;
                list($province,$city) = explode('-',$provinceCity);
                $async_key = $async_key == '同上' ?$preasync_key:$async_key;//异步通知key
                $wechat_code = $wechat_code == '同上' ?$prewechat_code:$wechat_code;//商户激活码
                $business_password = $business_password == '同上' ?$prebusiness_password:$business_password;//营业员密码
                $no_password = $no_password == '同上'?$preno_password:(trim($no_password) == 'NO'?2:1);//是否免密
                $province = trim($province);
                $city = !empty($city)?trim($city):$province;
                // ALTER TABLE `pay_merchant`
// ADD COLUMN `mchid`  varchar(50) NOT NULL DEFAULT '' COMMENT '商户号' AFTER `name`,
// ADD COLUMN `alipay`  enum('1','2') NOT NULL DEFAULT '2' COMMENT '微信开户:1=审核中,2=是' AFTER `wechat`,
// ADD COLUMN `ali_account`  varchar(255) NOT NULL DEFAULT '' COMMENT '支付宝商户号' AFTER `wechat_account`;


                $store = trim($store);
                $existsKey = $city.$store;
                if (isset($exists[$existsKey])) {
                    continue;
                }
                $exists[$existsKey] = 1;

                $insert[] = [
                    'name'=>$name,
                    'type'=>trim($type) == '个人'?1:2,
                    'province'=>$province,
                    'mchid'=>$mchid,
                    'ali_account'=>$ali_account,
                    'mchid'=>$mchid,
                    'city'=> !empty($city)?$city:$province,
                    'wechat'=>trim($wechat) == '是'?2:1,
                    'alipay'=>trim($alipay) == '是'?2:1,
                    'store'=>$store,
                    'code'=>$code,
                    'business_account'=>$business_account,
                    'business_password'=>$business_password,
                    'refund_password'=>$refund_password,
                    'wechat_account'=>$wechat_account,
                    'wechat_code'=>$wechat_code,
                    'async_key'=>$async_key,
                    'no_password'=>$no_password,
                    'quota'=>trim($type) == '个人'?600000:1200000,
                    'today_quota'=>trim($type) == '个人'?600000:1200000,
                    'quota_time'=>strtotime(date('Ymd')),
                    'token'=>'',
                    'createtime'=>time(),
                    'updatetime'=>time(),
                ];
                $preasync_key = $async_key;//异步通知key
                $prewechat_code = $wechat_code;//商户激活码
                $prebusiness_password = $business_password;//营业员密码
                $preno_password = $no_password;//是否免密
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }
        try {
            foreach ($insert as $key => $value) {
                $where = [
                    'city'=>$value['city'],
                    'store'=>$value['store'],
                ];
                $existsOne = \think\Db::table('pay_merchant')->where($where)->find();
                if ($existsOne) {
                    unset($value['createtime']);
                    unset($value['quota_time']);
                    \think\Db::table('pay_merchant')->where($where)->update($value);
                    unset($insert[$key]);
                }
            }
            \think\Db::table('pay_merchant')->insertAll($insert);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }
    public function updatecache()
    {
        (new \app\api\controller\Pay)->login();
        $this->success();
    }
}
